package com.hutu;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

public class TwoSum {

    /**
     * 两数和
     */
    public static int[] twoSum(int[] nums, int target) {
        if (nums == null) {
            return null;
        }
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i++) {
            if (map.get(nums[i]) != null) {
                return new int[]{i, map.get(nums[i])};
            }
            map.put(target - nums[i], i);
        }
        return null;
    }

    /**
     * 三数之和
     *
     * @param nums
     * @return
     */
    public static List<List<Integer>> threeSum(int[] nums) {
        if (nums == null || nums.length < 3) {
            return new ArrayList<>();
        }
        List<List<Integer>> res = new ArrayList<>();
        Arrays.sort(nums);
        int left = 0;
        int right = nums.length - 1;

        while (left < right) {
            int mid = (right + left) / 2;
            if (findMid(nums, left, mid, right, res)) {
                if (nums[right - 1] == nums[right]) {
                    right -= 2;
                } else {
                    right--;
                }
            } else {
                if (nums[left + 1] == nums[left]) {
                    left += 2;
                } else {
                    left++;
                }
            }
        }
        return res;
    }

    public static boolean findMid(int[] nums, int left, int mid, int right, List<List<Integer>> res) {
        int temp = mid;
        int dd = -nums[left] - nums[right];
        while (mid < right && mid > left) {

            if (dd == nums[mid]) {
                int finalMid = mid;
                res.add(new ArrayList<Integer>() {{
                    add(nums[left]);
                    add(nums[finalMid]);
                    add(nums[right]);
                }});
                break;
            } else if (nums[mid] > dd) {
                mid--;
            } else if (nums[mid] < dd) {
                mid++;
            }
        }
        return mid < temp;
    }

    public static void main(String[] args) {
        System.out.println(Arrays.toString(twoSum(new int[]{2, 4, 6, 5, 2}, 9)));
    }
}
